package gejw.android.wifimandatoryconnection.Wifi;

import gejw.android.wifimandatoryconnection.Wifi.Listener.WifiListener;
import gejw.android.wifimandatoryconnection.Wifi.Listener.WifiListener.WifiChangeCallBack;
import gejw.android.wifimandatoryconnection.Wifi.Utils.Toast;
import gejw.android.wifimandatoryconnection.Wifi.Utils.WifiUtils;
import gejw.android.wifimandatoryconnection.Wifi.Utils.WifiUtils.WifiState;

import java.util.List;

import android.content.Context;
import android.net.wifi.WifiConfiguration;
import android.net.wifi.WifiInfo;
import android.net.wifi.WifiManager;

public class WIFITools implements WifiChangeCallBack {
	public enum WifiCipherType {
		WIFICIPHER_NOPASS, WIFICIPHER_WEP, WIFICIPHER_WPA

	}

	private static WIFITools wifiTools = null;

	public static WIFITools getInstance(Context context,
			WifiChangeCallBack callBack) {
		if (wifiTools == null)
			wifiTools = new WIFITools(context, callBack);
		return wifiTools;
	}

	private Context mContext = null;
	private WifiManager mWifiManager = null;
	private WifiChangeCallBack mWifiChangeCallBack = null;
	private String lockWifiSSID = "";
	private String lockWifiPassword = "";
	private WifiCipherType lockWifiCipherType = WifiCipherType.WIFICIPHER_NOPASS;
	private boolean isLockWifi = false;

	public WIFITools(Context context, WifiChangeCallBack callBack) {
		mContext = context;
		mWifiChangeCallBack = callBack;
		mWifiManager = (WifiManager) mContext
				.getSystemService(Context.WIFI_SERVICE);
	}

	/**
	 * 开始监听wifi
	 * 
	 * @param callBack
	 */
	public void startWifiListener() {
		WifiListener.getInstance(mContext).setmWifiChangeCallBack(this).start();
	}

	/**
	 * 停止监听wifi
	 */
	public void stopWifiListener() {
		WifiListener.getInstance(mContext).stop();
	}

	/**
	 * 锁定wifi
	 */
	public void lockWifi(String SSID, String Password, WifiCipherType Type) {
		isLockWifi = true;

		lockWifiSSID = SSID;
		lockWifiPassword = Password;
		lockWifiCipherType = Type;

		// 生成配置
		WifiConfiguration wifiConfig = createWifiInfo(lockWifiSSID,
				lockWifiPassword, lockWifiCipherType);
		// 添加新的配置
		int networkId = mWifiManager.addNetwork(wifiConfig);
		mWifiManager.enableNetwork(networkId, true);

	}

	/**
	 * 解锁wifi
	 */
	public void unlockWifi() {
		isLockWifi = false;
	}

	/**
	 * 获取wifi状态
	 * 
	 * @return
	 */
	public WifiState getWifiState() {
		return WifiUtils.State2State(mWifiManager.getWifiState());
	}

	public String getWifiSSID() {
		WifiManager wm = (WifiManager) mContext
				.getSystemService(Context.WIFI_SERVICE);
		WifiInfo info = wm.getConnectionInfo();
		if (info != null && info.getSSID() != null) {
			return WipeQuotes(info.getSSID());
		}
		return "";
	}

	/**
	 * 修改ssid
	 * 
	 * @param ssid
	 */
	public void changeSSID(String ssid) {
		List<WifiConfiguration> wcList = mWifiManager.getConfiguredNetworks();
		if (wcList != null)
			for (WifiConfiguration wc : wcList) {
				if (wc.SSID.equals(String.format("\"%s\"", ssid))) {
					mWifiManager.enableNetwork(wc.networkId, true);
				}
			}
	}

	/**
	 * 检测是否存在ssid配置
	 * 
	 * @param ssid
	 * @return
	 */
	public WifiConfiguration isExistWifiConfig(String ssid) {
		List<WifiConfiguration> wcList = mWifiManager.getConfiguredNetworks();
		if (wcList != null)
			for (WifiConfiguration wc : wcList) {
				if (wc.SSID.equals(String.format("\"%s\"", ssid))) {
					return wc;
				}
			}
		return null;
	}

	@Override
	public void WifiChanged(String ssid) {
		ssid = WipeQuotes(ssid);
		if (mWifiChangeCallBack != null)
			mWifiChangeCallBack.WifiChanged(ssid);
		if (isLockWifi) {
			// 锁定wifi
			System.out.println("当前ssid--->" + ssid + "  当前状态--->"
					+ getWifiState());
			if (!ssid.equals(lockWifiSSID)) {
				Toast.show(mContext, String.format(
						"这是非法操作！\n您的wifi切换到了%s\n系统将切换回%s", ssid, lockWifiSSID));
				lockWifi(lockWifiSSID, lockWifiPassword, lockWifiCipherType);
			}
		}
	}

	@Override
	public void WifiStateChanged(WifiState state) {
		if (mWifiChangeCallBack != null)
			mWifiChangeCallBack.WifiStateChanged(state);
	}

	@Override
	public void WifiChanged() {
		if (mWifiChangeCallBack != null)
			mWifiChangeCallBack.WifiChanged();
	}

	/**
	 * 去除引号
	 */
	private String WipeQuotes(String str) {
		return str.startsWith("\"") ? str.substring(1, str.length() - 1) : str;
	}

	  public WifiConfiguration createWifiInfo(String SSID, String password, WifiCipherType type) {
          
          WifiConfiguration config = new WifiConfiguration();
          config.allowedAuthAlgorithms.clear();
          config.allowedGroupCiphers.clear();
          config.allowedKeyManagement.clear();
          config.allowedPairwiseCiphers.clear();
          config.allowedProtocols.clear();
          config.SSID = "\"" + SSID + "\"";

          WifiConfiguration tempConfig = isExistWifiConfig(SSID);
          if (tempConfig != null) {
                  mWifiManager.removeNetwork(tempConfig.networkId);
          }
          
          // 分为三种情况：1没有密码2用wep加密3用wpa加密
          if (type == WifiCipherType.WIFICIPHER_NOPASS) {// WIFICIPHER_NOPASS
                  config.wepKeys[0] = "";
                  config.allowedKeyManagement.set(WifiConfiguration.KeyMgmt.NONE);
                  config.wepTxKeyIndex = 0;
                  
          } else if (type == WifiCipherType.WIFICIPHER_WEP) {  //  WIFICIPHER_WEP 
                  config.hiddenSSID = true;
                  config.wepKeys[0] = "\"" + password + "\"";
                  config.allowedAuthAlgorithms
                                  .set(WifiConfiguration.AuthAlgorithm.SHARED);
                  config.allowedGroupCiphers.set(WifiConfiguration.GroupCipher.CCMP);
                  config.allowedGroupCiphers.set(WifiConfiguration.GroupCipher.TKIP);
                  config.allowedGroupCiphers.set(WifiConfiguration.GroupCipher.WEP40);
                  config.allowedGroupCiphers
                                  .set(WifiConfiguration.GroupCipher.WEP104);
                  config.allowedKeyManagement.set(WifiConfiguration.KeyMgmt.NONE);
                  config.wepTxKeyIndex = 0;
          } else if (type == WifiCipherType.WIFICIPHER_WPA) {   // WIFICIPHER_WPA
                  config.preSharedKey = "\"" + password + "\"";
                  config.hiddenSSID = true;
                  config.allowedAuthAlgorithms
                                  .set(WifiConfiguration.AuthAlgorithm.OPEN);
                  config.allowedGroupCiphers.set(WifiConfiguration.GroupCipher.TKIP);
                  config.allowedKeyManagement.set(WifiConfiguration.KeyMgmt.WPA_PSK);
                  config.allowedPairwiseCiphers
                                  .set(WifiConfiguration.PairwiseCipher.TKIP);
                  // config.allowedProtocols.set(WifiConfiguration.Protocol.WPA);
                  config.allowedGroupCiphers.set(WifiConfiguration.GroupCipher.CCMP);
                  config.allowedPairwiseCiphers
                                  .set(WifiConfiguration.PairwiseCipher.CCMP);
                  config.status = WifiConfiguration.Status.ENABLED;
          } 
          
          return config;
  }


}
